var express = require('express');
var router = express.Router();

const { aesDecrypt, checkSession } = require('../utils/index');  // 解密
const { MoviesModel } = require('../utils/model')


// express 里面的路由配置
// 很久不同的 url 匹配对应的路由模块，加载对应的数据和页面


// get: get请求
// req: 请求 request
// res: 响应 response
// next 进入下一个中间件
// res.render: 渲染模板
// title: 渲染模板里面的变量


router.get('/', function (req, res, next) {
  console.log(req.session);
  res.render('index', {
    title: '电影展示系统',
    username: req.session.username,
    phone: req.session.phone,
    loginTime: req.session.loginTime,
  });
});

router.get('/login', (req, res) => {
  // 解密函数的参数必须存在，不让会报错
  const username = req.query.username ? aesDecrypt(req.query.username) : '';
  res.render('login', {
    username
  });
})

// 注销
router.get('/logout', (req, res) => {
  req.session.destroy(() => {
    res.redirect('/');
  });  // 销毁 session
})

router.get('/register', (req, res) => {
  res.render('register');
})

router.get('/about', (req, res) => {
  if (req.session.username) {
    res.render('about', {
      username: req.session.username,
    });
  } else {
    res.send(`<script>alert('session已过期，请重新登陆');location.href='/login';</script>`);
  }
})

router.get('/mine', (req, res) => {
  if (req.session.username) {
    res.render('mine', {
      username: req.session.username,
    });
  } else {
    res.send(`<script>alert('session已过期，请重新登陆');location.href='/login';</script>`);
  }
})

router.get('/movies', (req, res) => {
  checkSession(req, res, username => {
    const query = req.query
    console.log(query);

    var searchObj = {};
    var sortObj = {};

    if (query.keyword) {
      // 搜索
      searchObj = {
        $or: [
          { title: new RegExp(query.keyword) },
          { year: new RegExp(query.keyword) },
          { 'rating.average': new RegExp(query.keyword) },
          { genres: new RegExp(query.keyword) },
        ]
      }
    } else {
      // 排序
      sortObj = query
    }

    MoviesModel.find({ ...searchObj }, { _id: 0 })
      .sort(sortObj)
      .then(result => {
        // console.log(result);
        res.render('movies', { username, result });
      })
  })
})





/* GET home page. */
router.get('/demo', function(req, res, next) {
  res.render('demo', {
    title: 'Express',
    word: '天道酬勤',
    news: '<u>今日热点新闻</u>',
    username: '老山羊',
    list: ['小胡鸭', '小黄鸭','大白鹅', '老山羊']
  });  // 完整写法 res.render('../views/demo.ejs', { title: 'Express' })
});



// 参数
// : ?
// : 声明的是动态路由参数，可以用 req.params 获取
// ? 表示该参数可传可不传，去掉问号则该参数必传
router.get('/goods/:gid?', (req, res) => {
  // res.send(req.params.gid)
  res.json({
    msg: '获取商品信息成功',
    result: null,
    params: req.params
  })
})

router.get('/userinfo', (req, res) => {
  res.json({
    msg: '获取用户信息成功',
    url: req.url,
    query: req.query,  // 获取查询参数
    path: req.path,
    headers: req.headers
  })
})

router.all('/allreq', (req, res) => {
  res.send('router.all()--表示这个接口既可以post请求也可以是get请求')
})

router.post('/postdata', (req, res) => {
  // res.send('1111111111111111111')
  res.json({
    msg: '这是一个post请求',
    body: req.body,
    query: req.query
  })
})

module.exports = router;
